﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using System.Web.Security;
using COM.Data;
using COM.Service;
using COM.Web;
using SampleApp.Data;
using SampleApp.Service;
using SampleApp.Domain;
using System.Xml.Linq;

namespace SampleApp.Web.Service
{
    public interface IAppUserPrincipalFactory : IUserPrincipalFactory
    {
        IPermissionUserPrincipal CreateSampleUserPrincipal(string userCode, string userName, string deptCode);
    }

    public class AppUserPrincipalFactory : UserPrincipalFactory, IAppUserPrincipalFactory
    {
        private IPermissionRoleListService permissionRoleListService;
        public AppUserPrincipalFactory(IPermissionRoleListService permissionRoleListService)
            : base(permissionRoleListService)
        {
            this.permissionRoleListService = permissionRoleListService;
        }

        public IPermissionUserPrincipal CreateSampleUserPrincipal(string userCode, string userName, string deptCode)
        {
            //权限系统不依赖于数据库服务,否则可能在IRuntimeService集成时会循环引用
            var sysUserService = Unity.Instance.GetService<ISysUserService>();
            var roleNameList = sysUserService.GetRoleListByUser(userCode);
            var roleItemList = roleNameList.Select(i => this.CreateAppUser(i, userCode, deptCode)).ToList();
            roleItemList.Add(WebUserPermissionRole.Instance);
            roleItemList.Add(new SampleApp.Data.AppEveryOne(userCode));
            var user = new PermissionUserPrincipal(userCode,userName,roleItemList);
            return user; ;
        }

        public PermissionRole CreateAppUser(string roleName, string userCode,string deptCode)
        {
            var roleType = this.permissionRoleListService.GetRoleTypeByName(roleName);
            if (roleType == null)
                throw new AppException("角色{0}未注册", roleName);
            var roleItem = Activator.CreateInstance(roleType) as PermissionRole;
            XElement xml = null;
            if (roleItem is AppEmployee)
                xml = new XElement("x", new XAttribute("UserCode", userCode), new XAttribute("DeptCode", deptCode));
            else if (roleItem is AppEveryOne)
                xml = new XElement("x", new XAttribute("UserCode", userCode));
            
            roleItem.ParseXml(xml);
            return roleItem;
        }

    }
}